package com.activities;


import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.Adapters.ProfileAdapter;
import com.Adapters.Items.ItemProfile;
import com.Adapters.Items.RowType;
import com.Animations.AnimUtil;
import com.Animations.AnimUtil.AnimationCompleted;
import com.Data.Post.onUploadPictureCompleted;
import com.Data.SocialInfo;
import com.Data.SocialInfo.onGetSocialInfoCompleted;
import com.Data.User;
import com.Data.User.onDeleteCompleted;
import com.Data.User.onGetUserInfoCompleted;
import com.Data.User.onUpdateInfoCompleted;
import com.Dialogs.DialogCover;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Downloaders.ThumbDownloader;
import com.Downloaders.ThumbDownloader.ThumbnailPathCompleted;
import com.Enums.BlurType;
import com.Location.MyLocationManager;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureIntentManagerClass;
import com.Managers.PictureManagerClass.CreateBlurAsync;
import com.Managers.PictureManagerClass.OnBlurCompleted;
import com.Managers.ThemeManager;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.UploadClasses.UploadManager;
import com.shareup.R;
import com.utils.ShowToastClass;


public class ActivityProfile extends Activity {

    public static final int CROPED_PICTURE_PROFILE = 600;

    public static final int SELECT_PHOTO_PROFILE = 500;

    public static final int SEND_TO_COVER = 800;

    public static final int SEND_TO_CROP_PROFILE = 700;

    private static final int ITEM_DESC = 0;

    private static final int ITEM_EMAIL = 2;

    private static final int ITEM_LOCATION = 3;

    private static final int ITEM_SEX = 1;

    private final OnClickListener backClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            exit();

        }
    };

    private final OnClickListener cClick = new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            showDialogCover();

        }
    };

    private ImageView container;

    private ImageView editProfile;

    private TextView followers;

    private TextView followersCounter;

    private TextView following;

    private TextView followingCounter;

    private boolean hasCover;

    private TextView header;

    private ListView list;

    private final OnItemClickListener listClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

            ProfileAdapter adapter = (ProfileAdapter) list.getAdapter();

            int pos = Integer.parseInt(v.getTag().toString());
            switch (pos) {
                case ITEM_SEX:
                    break;
                case ITEM_LOCATION:
                    showDialogMaps(v);
                    break;
                case ITEM_EMAIL:
                    showDialogEditText(adapter.getItem(position), true);
                    break;
                default:
                    showDialogEditText(adapter.getItem(position), false);
                    break;
            }

        }

    };

    private ActivityProfile me;

    private View mEditCover;

    private ImageView mProfile;

    private final OnLongClickListener nameClick = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            TextView tV = (TextView) v;
            String text = (String) tV.getText();
            showDialogEditText(text);
            return false;
        }
    };

    private TextView nombre;

    private final OnClickListener pClick = new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            changeProfilePicture();

        }
    };

    private TextView pictures;

    private TextView picturesCounter;

    private TextView preferences_text;

    private View progress;

    private ProgressBar progressCover;

    private Uri selectedImage = null;

    private RelativeLayout socialInfo;

    private final OnClickListener startPrefs = new OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent intent = new Intent(v.getContext(), ActivityPreferences.class);
            v.getContext().startActivity(intent);
            AnimUtil.getActivityTransition(me, true);

        }
    };

    boolean hasChanged = false;

    public void changeCoverPicture() {

        startActivityForResult(PictureIntentManagerClass.createPictureChooser(), ActivityProfile.SEND_TO_COVER);
    }

    public void deletePictureCover() {

        User us = new User();

        String oldCover = UserManagerClass.UserLogged.getCoverPicture();

        if (!oldCover.equals("null")) {
            int startIndex = oldCover.lastIndexOf("/");
            int lastIndex = oldCover.length();
            if (startIndex != 0)
                oldCover = oldCover.substring(startIndex, lastIndex);

        }

        us.setCoverPicture(oldCover);
        us.setID(UserManagerClass.UserLogged.getID());
        us.setCallbackDelete(new onDeleteCompleted() {

            @Override
            public void Completed(String result) {

                hasCover = false;
                AnimUtil.AnimateDrawablesOutImage(container);

            }
        });
        us.execute(User.ACTION_DELETE_COVER);
        UserManagerClass.UserLogged.setCoverPicture("null");

    }

    public void downloadCover(String path) {

        if (path != null && !path.equals("null")) {

            hasCover = true;
            ThumbDownloader td = new ThumbDownloader(this, path);
            td.setCover(true);
            td.setCompletePath(new ThumbnailPathCompleted() {

                @Override
                public void Completed(String path) {

                    int Blur = BlurType.BLUR_COVER.getValue();
                    if (UserManagerClass.UserLogged.getBlur() == 0)
                        Blur = 0;

                    CreateBlurAsync cbs = new CreateBlurAsync(Blur, container, path, new OnBlurCompleted() {

                        @Override
                        public void Completed() {

                            AnimUtil.AnimateFadeOutIn(mEditCover, true, null, progressCover);

                        }
                    });
                    cbs.setUserProfile(true);
                    cbs.execute();

                }
            });
            td.execute();

        }
        else
            AnimUtil.AnimateFadeOutIn(mEditCover, true, null, progressCover);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    public void showDialogMaps(final View view) {

        if (view.getTag().equals(ProfileAdapter.ITEM_LOCATION)) {

            Double latitude = UserManagerClass.UserLocation.getLatitude();
            Double longitude = UserManagerClass.UserLocation.getLongitude();

            Intent intent = new Intent(this, ActivityMap.class);

            Bundle extras = new Bundle();
            extras.putDouble("latitud", latitude);
            extras.putDouble("longitud", longitude);
            extras.putString("owner", UserManagerClass.UserLogged.getRealName());
            extras.putString("picture", UserManagerClass.UserLogged.getProfilePicture());
            extras.putString("local", UserManagerClass.UserLocation.toString());
            extras.putBoolean("mine", true);
            extras.putInt("type", RowType.TEXT_POST.ordinal());
            intent.putExtras(extras);

            startActivity(intent);
            AnimUtil.getActivityTransition(this, true);

        }

    }

    private void changeProfilePicture() {

        startActivityForResult(PictureIntentManagerClass.createPictureChooser(), ActivityProfile.SEND_TO_CROP_PROFILE);
    }

    private void delayTask(final SocialInfo sinfo, final int time) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                sinfo.execute(0, -1);
            }
            //
        }, time);
    }

    private void downloadProfilePicture(final ImageView profile, boolean download) {

        progress.setVisibility(View.VISIBLE);
        // DONT DOWNLOAD IF ITS THE FIRST TIME ENTERING TO THE PROFILE, SET FROM
        // MENU THE PROFILE PICTURE
   
            User us = new User();
            us.setCallbackGetInfo(new onGetUserInfoCompleted() {

                @Override
                public void Completed(User result) {

                    ProfilePictureDownloader pd = new ProfilePictureDownloader();
                    pd.setProgress(progress);
                    pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

                        @Override
                        public void completed(Bitmap result) {
                            AnimUtil.animatePictureChanges(mProfile, result);
                           
                        }
                    });
                    pd.execute(UserManagerClass.UserLogged.getProfilePicture());

                }
            });
            us.execute(User.ACTION_GET_INFO);
        }

   

    private void downloadSocialInfo() {

        SocialInfo sinfo = new SocialInfo();
        sinfo.setIDUser(UserManagerClass.UserLogged.getID());
        sinfo.setCallbackGetSocialInfo(new onGetSocialInfoCompleted() {

            @Override
            public void Completed(SocialInfo result) {

                setSocialInfo(result);

            }
        });
        this.delayTask(sinfo, 500);
    }

    private void downloadUserInfo() {

        setProfileInfo(UserManagerClass.UserLogged);
    }

    private void exit() {

        if (hasChanged)
            updateProfile();
        else {
            FragmentManagerClass.aProfile = null;
            finish();
            AnimUtil.getActivityTransition(this, false);
        }

    }

    private void inicializar() {

        me = this;
        FragmentManagerClass.aProfile = this;

        if (UserManagerClass.UserLocation == null)
            MyLocationManager.updateMyLocation(this);

        if (UserManagerClass.UserLogged == null)
            UserManagerClass.UserLogged = new UserManagerClass(this).getInfo();

        ImageView backB = (ImageView) findViewById(R.id.button_back);
        header = (TextView) findViewById(R.id.aprofile_header);
        UtilFonts.setTextBoldFont(header);
        backB.setOnClickListener(backClick);
        container = (ImageView) this.findViewById(R.id.coverView);
        list = (ListView) this.findViewById(R.id.list_profile_edit);
        list.setVisibility(View.INVISIBLE);
        //
        progress = findViewById(R.id.loading_progress);
        editProfile = (ImageView) this.findViewById(R.id.menu_change_profile);
        editProfile.setOnClickListener(pClick);

        mEditCover = this.findViewById(R.id.menu_edit_cover);
        mEditCover.setOnClickListener(cClick);
        mEditCover.setVisibility(View.INVISIBLE);
        //
        progressCover = (ProgressBar) findViewById(R.id.loading_cover);
        //
        preferences_text = (TextView) findViewById(R.id.preferences_text);
        preferences_text.setOnClickListener(startPrefs);
        UtilFonts.setTextBoldFont(preferences_text);
        //
        mProfile = (ImageView) this.findViewById(R.id.aprofile_image);
        mProfile.setTag(UserManagerClass.UserLogged.getID());

        nombre = (TextView) this.findViewById(R.id.ap_profile_name);
        UtilFonts.setTextBoldFont(nombre);
        nombre.setText(UserManagerClass.UserLogged.getRealName());
        //
        nombre.setOnLongClickListener(nameClick);
        setTextInfo();
        //
        downloadProfilePicture(mProfile, false);
        //
        downloadSocialInfo();
    }

    /**
     * @param result
     *            Result with the new profile image url
     */
    private void postUpload(String result) {

        new File(DirManagerClass.getPathPicture(UserManagerClass.UserLogged.getProfilePicture())).delete();

        AnimUtil.AnimateDrawablesOutImage(mProfile, mProfile.getDrawable());
        UserManagerClass.UserLogged.setProfilePicture(result);

        new UserManagerClass(this).saveInfo(UserManagerClass.UserLogged);

        downloadProfilePicture(mProfile, true);

    }

    private void setProfileInfo(User info) {

        ProfileAdapter adapter = new ProfileAdapter(this);
        //
        String desc = getResources().getString(R.string.string_no_description);
        if (!info.getDescription().equals("")) {
            desc = info.getDescription();
        }
        adapter.add(new ItemProfile(desc, R.drawable.user_state_icon, ITEM_DESC, false));
        String sex = this.getResources().getString(R.string.login_female);
        if (info.getSex() == 0) {
            sex = this.getResources().getString(R.string.login_male);
        }
        adapter.add(new ItemProfile(sex, R.drawable.user_sex, ITEM_SEX, false));
        adapter.add(new ItemProfile(info.getEmail(), R.drawable.user_email_icon, ITEM_EMAIL, false));
        //
        if (UserManagerClass.UserLocation != null) {
            String location = String.format(getString(R.string.crop_location), UserManagerClass.UserLocation.getAddress());
            adapter.add(new ItemProfile(location, R.drawable.add_location_icon_normal, ITEM_LOCATION, true));
        }

        list.setAdapter(adapter);
        AnimUtil.animateFadeIn(list);
        list.setOnItemClickListener(listClick);

        // DOWNLOADE THE COVER
        downloadCover(UserManagerClass.UserLogged.getCoverPicture());

    }

    private void setProfilePicture(Uri path) {

        if (path != null) {
            selectedImage = path;
            PictureIntentManagerClass.performCrop(this, selectedImage);
        }
    }

    private void setSocialInfo(SocialInfo info) {

        String f = getString(R.string.profile_followers);
        String ll = getString(R.string.profile_followings);
        String p = getString(R.string.profile_pictures);
        //
        this.followers.setText(f);
        this.following.setText(ll);
        this.pictures.setText(p);
        //
        this.picturesCounter.setText(String.valueOf(info.getPictures()));
        this.followersCounter.setText(String.valueOf(info.getFollowers()));
        this.followingCounter.setText(String.valueOf(info.getFollowing()));
        //
        AnimUtil.animateFadeIn(socialInfo);

        this.downloadUserInfo();
    }

    private void setTextInfo() {

        socialInfo = (RelativeLayout) findViewById(R.id.table_info);
        socialInfo.setVisibility(View.INVISIBLE);
        //
        followers = (TextView) this.findViewById(R.id.aprofile_followers);
        pictures = (TextView) this.findViewById(R.id.aprofile_pictures);
        following = (TextView) this.findViewById(R.id.aprofile_following);
        //
        picturesCounter = (TextView) this.findViewById(R.id.profile_p_counter);
        followersCounter = (TextView) this.findViewById(R.id.profile_e_counter);
        followingCounter = (TextView) this.findViewById(R.id.profile_f_counter);
        //
        UtilFonts.setTextRegularFont(picturesCounter);
        UtilFonts.setTextRegularFont(followingCounter);
        UtilFonts.setTextRegularFont(followersCounter);
        //
        UtilFonts.setTextRegularFont(following);
        UtilFonts.setTextRegularFont(pictures);
        UtilFonts.setTextRegularFont(followers);
        //
    }

    private void showDialogCover() {

        DialogCover dc = new DialogCover(this, hasCover);
        dc.setProfile(this);
        dc.show();

    }

    private void showDialogEditText(final ItemProfile prof, final boolean email) {

        AlertDialog.Builder dg = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_add_comment, null);
        // ///////////////////////////////////////////////////////////////////////////////////////////////////////
        Button button = (Button) v.findViewById(R.id.dialog_tag_OK);
        final EditText optionedit = (EditText) v.findViewById(R.id.commentext);
        optionedit.setGravity(Gravity.CENTER_HORIZONTAL);
        optionedit.setText(prof.tag);
        optionedit.setSelection(prof.tag.length());
        // /////////////////////////////////////////////////////////////////////////
        UtilFonts.setTextRegularFont(optionedit);
        UtilFonts.setTextRegularFont(button);
        // //////////////////////////////////////////////////////////////////
        dg.setView(v);
        // /////////////////////////////////////////////
        final AlertDialog alert = dg.create();
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (email) {
                    if (!optionedit.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")) {
                        optionedit.setError(v.getResources().getString(R.string.error_email_match));
                    }
                    else {
                        if (!prof.tag.equals(optionedit.getText().toString())) {
                            hasChanged = true;
                            prof.tag = optionedit.getText().toString();
                        }
                        alert.cancel();
                    }
                }
                else {
                    if (!prof.tag.equals(optionedit.getText().toString())) {
                        hasChanged = true;
                        prof.tag = optionedit.getText().toString();
                    }
                    alert.cancel();
                }
            }
        });
        //
        alert.show();
    }

    private void showDialogEditText(final String text) {

        AlertDialog.Builder dg = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_add_comment, null);
        // ///////////////////////////////////////////////////////////////////////////////////////////////////////
        Button button = (Button) v.findViewById(R.id.dialog_tag_OK);
        final EditText optionedit = (EditText) v.findViewById(R.id.commentext);
        optionedit.setGravity(Gravity.CENTER_HORIZONTAL);
        optionedit.setText(text);
        optionedit.setSelection(text.length());
        // /////////////////////////////////////////////////////////////////////////
        UtilFonts.setTextRegularFont(optionedit);
        UtilFonts.setTextRegularFont(button);
        // //////////////////////////////////////////////////////////////////
        dg.setView(v);
        // /////////////////////////////////////////////
        final AlertDialog alert = dg.create();
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (nombre.length() <= 3) {
                    optionedit.setError(nombre.getResources().getString(R.string.error_field_username_short));
                }
                else {
                    if (!nombre.getText().equals(optionedit.getText().toString())) {
                        hasChanged = true;
                        nombre.setText(optionedit.getText().toString());
                    }
                    alert.cancel();
                }
            }
        });
        //
        alert.show();
    }

    private void updateProfile() {

        ProfileAdapter adapter = (ProfileAdapter) list.getAdapter();
        String email = adapter.getItem(ITEM_EMAIL).tag;
        String realname = nombre.getText().toString();
        String desc = adapter.getItem(ITEM_DESC).tag;

        final User user = UserManagerClass.UserLogged;
        user.setEmail(email);
        user.setRealName(realname);
        user.setDescription(desc);

        User us = new User();
        us.setDescription(desc);
        us.setRealName(realname);
        us.setEmail(email);
        us.setID(UserManagerClass.UserLogged.getID());
        us.setContext(this);
        us.setCallbackUpdateInfo(new onUpdateInfoCompleted() {

            @Override
            public void Completed(String result) {

                if (result.equals("-10"))
                    ShowToastClass.message(getResources().getString(R.string.error_connection_timeout), list.getContext());
                else {
                    FragmentManagerClass.aMenu.setUserInfo(user);
                    hasChanged = false;
                    exit();
                }

            }
        });
        us.execute(User.ACTION_UPDATE);
    }

    private void uploadPictureCover(Uri picname) {

    	 UserManagerClass.UserLogged.setCoverPicture("null");
    	
          new UploadManager().UploadPictureCover(null, picname, this,        
          new onUploadPictureCompleted() {

              @Override
              public void Completed(final String result) {

            	  AnimUtil.AnimateFadeOutIn(progressCover, true, new AnimationCompleted() {

                      @Override
                      public void Completed() {

                          String[] res = result.split("#");
                          UserManagerClass.UserLogged.setCoverPicture(res[0]);
                          new UserManagerClass(getApplicationContext()).saveInfo(UserManagerClass.UserLogged);
                          downloadCover(res[0]);

                      }
                  }, mEditCover);
              }
          });
       
    }

    private void uploadPictureProfile() {

        PictureIntentManagerClass.uploadPicture(this, true, false, null, new onUploadPictureCompleted() {

            @Override
            public void Completed(String result) {

                postUpload(result);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent dataintent) {

        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, dataintent);
        //
        if (requestCode == ActivityProfile.SEND_TO_CROP_PROFILE) {
            if (resultCode == RESULT_OK) {
                Uri path = PictureIntentManagerClass.getImageUri(dataintent, false);

                setProfilePicture(path);

            }
        }
        else
            if (requestCode == ActivityProfile.SEND_TO_COVER) {
                if (resultCode == RESULT_OK) {
                    Uri path = PictureIntentManagerClass.getImageUri(dataintent, false);
                    String spath = PictureIntentManagerClass.getPath(path, this);
                    if (path != null) {
                        uploadPictureCover(Uri.parse(spath));
                     }                }
            }
            else
                if (requestCode == ActivityProfile.CROPED_PICTURE_PROFILE) {
                    if (resultCode == RESULT_OK) {
                        uploadPictureProfile();
                    }
                    else {
                        if (mProfile == null) {
                            finish();
                        }
                    }
                }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_edit);
        inicializar();

    }

    @Override
    protected void onResume() {

        if (mProfile == null)
            inicializar();

        super.onResume();

    }
}
